package com.example.stlink.fragments;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.stlink.R;
import com.example.stlink.activitys.fragmentChild.activityStuClassList.CourseSignIn;
import com.example.stlink.configs.adapter.StuClassListFragAdapter;
import com.example.stlink.configs.onRecyclerViewItemClickListener;
import com.example.stlink.model.constants.ModelFieldConstants;
import com.example.stlink.model.constants.UrlConstants;
import com.example.stlink.model.domain.Course;
import com.example.stlink.model.domain.CourseSign;
import com.example.stlink.model.response.BaseResponse;
import com.example.stlink.model.response.data.CourseData;
import com.example.stlink.utils.httpUtils.GetUrlParamHttpUtils;
import com.google.android.material.badge.BadgeDrawable;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

public class StuClassListFragment extends Fragment {

    private static RecyclerView rvStuCourseMsg;
    private static List<CourseSign> courseSigns;
    private static List<Long> courseIdList;
    private static StuClassListFragAdapter adapter;
    private static AppCompatActivity mAppCompatActivity;
    private static SwipeRefreshLayout srlMyRefresh;

    private static BadgeDrawable mBadge;

    private int currentPage = 1;
    private int size = 10;

    private static Bundle bundle;
    private static Handler handler;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_stu_class_msg, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    public static StuClassListFragment newInstance(String str, AppCompatActivity appCompatActivity, BadgeDrawable orCreateBadge){
        mAppCompatActivity = appCompatActivity;
        mBadge = orCreateBadge;
        StuClassListFragment frag = new StuClassListFragment();
        return frag;
    }

    private void initView(View view){
        rvStuCourseMsg = view.findViewById(R.id.rv_stu_course_msg);
        srlMyRefresh = view.findViewById(R.id.srl_my_refresh);
        srlMyRefresh.setColorSchemeColors(Color.parseColor("#ff0000"),Color.parseColor("#00ff00"));
        refreshData();
    }



    @SuppressLint("NotifyDataSetChanged")
    public static void refreshData(){
        courseIdList = new ArrayList<>();
        courseSigns = new ArrayList<>();
        adapter = new StuClassListFragAdapter(
                mAppCompatActivity,
                R.layout.card_class_unsigned_msg,
                courseSigns,
                0
        );
        LinearLayoutManager llm = new LinearLayoutManager(mAppCompatActivity);
        rvStuCourseMsg.setLayoutManager(llm);
        rvStuCourseMsg.setAdapter(adapter);

        bundle = mAppCompatActivity.getIntent().getExtras();

        getStuSelectedCourseList();
        //只有在获取当前学生所选课程的所有id之后才能遍历
        handler = new Handler(msg -> {
            if(msg.arg1 == 100){
                getToBeSignList();
                setListener();
            }else if(msg.arg1 == 200){
                adapter.notifyDataSetChanged();
                System.out.println("StuClassListFragment:courseSigns = " + courseSigns.toString());
            }
            return false;
        });

    }

    /**
     * 为每一项item设置按钮点击监听事件
     */
    private static void setListener(){
        adapter.setOnItemClickListener(new onRecyclerViewItemClickListener() {

            @Override
            public void onItemClick(RecyclerView parent, View view, int position) {
                CourseSign courseSign = courseSigns.get(position);
                bundle.putSerializable(ModelFieldConstants.COURSE_SIGN, courseSign);
                Intent intent = new Intent(mAppCompatActivity, CourseSignIn.class);
                intent.putExtras(bundle);
                mAppCompatActivity.startActivity(intent);
            }

            @Override
            public void onItemLongClick(RecyclerView parent, View view, int position) {

            }
        });
        srlMyRefresh.setOnRefreshListener(() -> {
            refreshData();
            srlMyRefresh.setRefreshing(false);
        });
    }

    /**
     * 获取学生选择的课程列表
     */
    private static void getStuSelectedCourseList(){
        new Thread(new Runnable() {
            final String urlParam = ModelFieldConstants.USER_ID + "=" + bundle.getLong(ModelFieldConstants.ID);
            final String url = UrlConstants.STUDENT_COURSE + "?" + urlParam;
            @Override
            public void run() {
                new GetUrlParamHttpUtils() {
                    @Override
                    public void nextMethod(BaseResponse<Object> baseResponse) {
                        System.out.println("StuClassListFragment:baseResponse : " + baseResponse);
                        //解析数据
                        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
                        Object obj = baseResponse.getData();
                        LinkedTreeMap<String, String> courseDataMap = null;
                        if(obj instanceof LinkedTreeMap){
                            courseDataMap = (LinkedTreeMap<String, String>) obj;
                        }
                        //将LinkedTreeMap中字段映射到CourseData类中
                        String jsonString = gson.toJson(courseDataMap);
                        CourseData<Course> courseData = gson.fromJson(jsonString, new TypeToken<CourseData<Course>>() {}.getType());

                        List<Course> records = courseData.getRecords();

                        for(Course course : records){
                            courseIdList.add(course.getmCourseId());
                        }

                        Message message = new Message();
                        message.arg1 = 100;
                        handler.sendMessage(message);
                    }
                    @Override
                    public void failedMethod(BaseResponse<Object> baseResponse) { }
                }.getConnect(url);
            }
        }).start();
    }


    /**
     * 获取已选课程待签到内容
     */
    private static void getToBeSignList(){
        new Thread(() -> {
            for(Long courseId : courseIdList){
                String urlParam = ModelFieldConstants.COURSE_ID + "=" + courseId + "&" +
                        ModelFieldConstants.USER_ID + "=" + bundle.getLong(ModelFieldConstants.ID) + "&" +
                        ModelFieldConstants.COURSE_SIGN_STATUS + "=" + 0;
                String url = UrlConstants.STUDENT_SIGN_LIST + "?" + urlParam;
                new GetUrlParamHttpUtils() {
                    @Override
                    public void nextMethod(BaseResponse<Object> baseResponse) {
                        if(baseResponse.getData() != null){
                            System.out.println("StuClassListFragment:courseDataBaseResponse.getData() = " + baseResponse.getData() + "...............");

                            //解析数据
                            Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
                            Object obj = baseResponse.getData();
                            LinkedTreeMap<String, String> courseDataMap = null;
                            if(obj instanceof LinkedTreeMap){
                                courseDataMap = (LinkedTreeMap<String, String>) obj;
                            }
                            //将LinkedTreeMap中字段映射到CourseData类中
                            //array:学生获取所选课程签到列表返回实体
                            String jsonString = gson.toJson(courseDataMap);
                            CourseData<CourseSign> courseData = gson.fromJson(jsonString, new TypeToken<CourseData<CourseSign>>() {}.getType());
                            for(CourseSign courseSign : courseData.getRecords()){
                                courseSign.setCourseId(courseId);
                            }
                            int total = courseData.getTotal();
                            //设置角标
                            mBadge.setVisible(true);
                            mBadge.setNumber(total);
                            System.out.println("StuClassListFragment:size = " + mBadge.getNumber() + ".....................");
                            System.out.println(mBadge.isVisible());
                            if(courseData.getRecords().size() != 0){
                                courseSigns.addAll(courseData.getRecords());
                                Message message = new Message();
                                message.arg1 = 200;
                                handler.sendMessage(message);
                            }
                        }
                    }
                    @Override
                    public void failedMethod(BaseResponse<Object> baseResponse) { }
                }.getConnect(url);
            }
        }).start();
    }
}
